using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using elibrary.Classes;
using elibrary.Models;
using elibrary.Models.Entities;

namespace elibrary.Models.Managers
{
	public class UserManager
	{
		private DataContext ctx;
		private DbSet<User> users;

		public UserManager(DataContext ctx)
		{
			this.ctx = ctx;
			this.users = ctx.users;
		}

		public void add(User user,bool autoSave=true)
		{
			users.Add(user);
			if (autoSave)
				ctx.SaveChanges();
		}

		public User get(int id)
		{
			return users.SingleOrDefault(q => q.id == id);
		}

		public bool has(int id)
		{
			return get(id) != null;
		}

		public User get(string loginId)
		{
			return users.SingleOrDefault(q => q.loginId == loginId);
		}

		public bool has(string loginId)
		{
			return get(loginId) != null;
		}

		public User getByEmail(string email)
		{
			return users.SingleOrDefault(q => q.email == email);
		}

		public bool hasByEmail(string email)
		{
			return getByEmail(email) != null;
		}

		public List<User> getAllInClientObject(string[] cols, int cuid)
		{
			List<Dictionary<string,object>> toReturn = new List<Dictionary<string,object>>();
			List<User> allUsers = Utilities.ensureRs<User>(users.Where(q => q.id != cuid));

			foreach(var user in allUsers)
			{
				Dictionary<string,object> toAdd = new Dictionary<string,object>();

				foreach(var col in cols)
				{
					if (col == "status")
					{
						toAdd["status"] = (int)user.status;
						continue;
					}

					toAdd[col] = Utilities.reflectProperty(user, col);
				}

				if (toAdd.Count > 0)
					toReturn.Add(toAdd);
			}

			return toReturn;
		}

		public void delete(int id,bool autoSave=true)
		{
			delete(get(id),autoSave);
		}

		public void delete(string loginId,bool autoSave=true)
		{
			delete(get(loginId),autoSave);
		}

		public void delete(User user,bool autoSave=true)
		{
			if (user == null)
				return;

			users.Remove(user);
			if (autoSave)
				ctx.SaveChanges();
		}
	}
}